<template>
  <!-- 规格弹窗 -->
  <su-popup :show="show" round="10" @close="emits('close')">
    <view class="ss-modal-box bg-white ss-flex-col">
      <view class="modal-header ss-flex ss-col-center">
        <view class="header-left ss-m-r-30">
          <image
            class="sku-image"
            :src="attr.image || goodsInfo.image"
            mode="aspectFill"
          ></image>
        </view>
        <view class="header-right ss-flex-col ss-row-between ss-flex-1">
          <view class="goods-title ss-line-2">{{ goodsInfo.storeName }}</view>
          <view class="header-right-bottom ss-flex ss-col-center ss-row-between">
            <view class="ss-flex">
              <view v-if="attr.price > 0" class="price-text">
                {{ attr.price ||goodsInfo.price }}
              </view>
              <view class="ss-flex">
                <view
                  v-if="attr.price > 0 && attr.score > 0"
                  class="score-text ss-m-l-4"
                  >+
                </view>
                <image
                  v-if="attr.score > 0"
                  :src="mall.$url.static('/static/img/shop/goods/score1.svg')"
                  class="score-img"
                >
                </image>
                <view v-if="attr.score > 0" class="score-text">
                  {{ attr.score }}
                </view>
              </view>
            </view>

            <view class="stock-text ss-m-l-20">
              {{
                state.attr.stock
                  ? formatStock(goodsInfo.stock_show_type,attr.stock)
                  : formatStock(goodsInfo.stock_show_type, goodsInfo.stock)
              }}
            </view>
          </view>
        </view>
      </view>
      <view class="modal-content ss-flex-1">
        <scroll-view scroll-y="true" class="modal-content-scroll" @touchmove.stop>
          <view class="sku-item ss-m-b-20" v-for="
          (sku1,i) in props.productAttr" :key="sku1.id">
            <view class="label-text ss-m-b-20">{{sku1.attrName}}:</view>
            <view class="ss-flex ss-col-center ss-flex-wrap">
              <button
                class="ss-reset-button spec-btn"
                v-for="(sku2,index) in sku1.attrValues.split(',')"
                :class="[
                  {
                    'ui-BG-Main-Gradient': state.currentSkuArray[i] ==  sku2,
                  },
                  
                ]"
                :key="index"
                @tap="onSelectSku(sku2,i)"
              >
                {{ sku2 }}
              </button>
            </view>
          </view>
          <view class="buy-num-box ss-flex ss-col-center ss-row-between ss-m-b-40">
            <view class="label-text">购买数量</view>
            <su-number-box
              :min="1"
              :max="attr.stock"
              :step="1"
              v-model="state.sku.cartNum"
              @change="onNumberChange($event)"
            ></su-number-box>
          </view>
        </scroll-view>
      </view>
      <view class="modal-footer border-top">
        <view
          class="buy-box ss-flex ss-col-center ss-flex ss-col-center ss-row-center"
          v-if="isScore"
        >
          <button class="ss-reset-button score-btn ui-Shadow-Main" @tap="onBuy">立即兑换</button>
        </view>
        <view class="buy-box ss-flex ss-col-center ss-flex ss-col-center ss-row-center" v-else>
          <button class="ss-reset-button add-btn ui-Shadow-Main" @tap="onAddCart"
            >加入购物车</button
          >
          <button class="ss-reset-button buy-btn ui-Shadow-Main" @tap="onBuy">立即购买</button>
        </view>
      </view>
    </view>
  </su-popup>
</template>

<script setup>
  import { computed, reactive, watch,ref } from 'vue';
  import mall from '@/mall';
  import { formatStock, formatPrice } from '@/mall/hooks/useGoods';
  import { isEmpty } from 'lodash';

  const emits = defineEmits(['change', 'addCart', 'buy', 'close']);
  const props = defineProps({
    goodsInfo: {
      type: Object,
      default:() =>{},
    },
    productAttr:{
      type: Object,
      default:() =>[], 
    },
        productValue:{
      type: Object,
      default:() =>{}, 
    },
    show: {
      type: Boolean,
      default: false,
    },
    isScore: {
      type: Boolean,
      default: false,
    },
  });
  let attr = ref({})
  const state = reactive({
    selectedSkuPrice: {},
    currentSkuArray: [],
    sku:{cartNum:1},
  });
  //输入框改变数量
  function onNumberChange(e) {
    if (e === 0) return;
    if (state.sku.cartNum === e) return;
    state.sku.cartNum = e;
  }


  function onAddCart() {
    if (state.sku.id) {
      if (attr.value.stock <= 0) {
        mall.$helper.toast('库存不足');
      } else {
        emits('addCart', state.sku);
      }
    } else {
      mall.$helper.toast('请选择规格');
    }
  }

  function onBuy() {
     if (state.sku.id) {
      if (attr.value.stock <= 0) {
        mall.$helper.toast('库存不足');
      } else {
        emits('buy', state.sku);
      }
    } else {
      mall.$helper.toast('请选择规格');
    }
  }

  // 选择规格
  function onSelectSku(name,i) {
    // 清空已选择
    let isChecked = true; // 选中 or 取消选中
    if (state.currentSkuArray[i] == name) {
      // 点击已被选中的，删除并填充 ''
      isChecked = false;
        state.currentSkuArray[i] = ''
    } else {
      // 选中
      state.currentSkuArray[i] = name
    }
    if (state.currentSkuArray.length == props.productAttr.length&&state.currentSkuArray.every(e=>!!e)) {
      dealAttr()
    }
  }
  function dealAttr() {
    let name = state.currentSkuArray.join(',')
    attr.value = props.productValue[name]
    state.sku = {id:attr.value.id,cartNum:1,productId:attr.value.productId,}
  }

  watch(
    () => state.sku,
    (newVal) => {
      emits('change', newVal);
    },
    {
      immediate: true, // 立即执行
      deep: true, // 深度监听
    },
  );
  // 默认单规格
  if (props.productAttr.length==1) {
    let name = props.productAttr[0].attrValues
    attr.value = props.productValue[name];
  }

  const skuList = props.goodsInfo.skus;


</script>

<style lang="scss" scoped>
  // 购买
  .buy-box {
    padding: 10rpx 0;

    .add-btn {
      width: 356rpx;
      height: 80rpx;
      border-radius: 40rpx 0 0 40rpx;
      background-color: var(--ui-BG-Main-light);
      color: var(--ui-BG-Main);
    }

    .buy-btn {
      width: 356rpx;
      height: 80rpx;
      border-radius: 0 40rpx 40rpx 0;
      background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
      color: #fff;
    }

    .score-btn {
      width: 100%;
      margin: 0 20rpx;
      height: 80rpx;
      border-radius: 40rpx;
      background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
      color: #fff;
    }
  }

  .ss-modal-box {
    border-radius: 30rpx 30rpx 0 0;
    max-height: 1000rpx;

    .modal-header {
      position: relative;
      padding: 80rpx 20rpx 40rpx;

      .sku-image {
        width: 160rpx;
        height: 160rpx;
        border-radius: 10rpx;
      }

      .header-right {
        height: 160rpx;
      }

      .close-icon {
        position: absolute;
        top: 10rpx;
        right: 20rpx;
        font-size: 46rpx;
        opacity: 0.2;
      }

      .goods-title {
        font-size: 28rpx;
        font-weight: 500;
        line-height: 42rpx;
      }

      .score-img {
        width: 36rpx;
        height: 36rpx;
        margin: 0 4rpx;
      }

      .score-text {
        font-size: 30rpx;
        font-weight: 500;
        color: $red;
        font-family: OPPOSANS;
      }

      .price-text {
        font-size: 30rpx;
        font-weight: 500;
        color: $red;
        font-family: OPPOSANS;

        &::before {
          content: '￥';
          font-size: 30rpx;
          font-weight: 500;
          color: $red;
        }
      }

      .stock-text {
        font-size: 26rpx;
        color: #999999;
      }
    }

    .modal-content {
      padding: 0 20rpx;

      .modal-content-scroll {
        max-height: 600rpx;

        .label-text {
          font-size: 26rpx;
          font-weight: 500;
        }

        .buy-num-box {
          height: 100rpx;
        }

        .spec-btn {
          height: 60rpx;
          min-width: 100rpx;
          padding: 0 30rpx;
          background: #f4f4f4;
          border-radius: 30rpx;
          color: #434343;
          font-size: 26rpx;
          margin-right: 10rpx;
          margin-bottom: 10rpx;
        }

        .disabled-btn {
          font-weight: 400;
          color: #c6c6c6;
          background: #f8f8f8;
        }
      }
    }
  }
</style>
